const ExcelJS = require('exceljs');
const path = require('path');
const fs = require('fs');

/**
 * 导出功能工具类
 * 提供Excel文件导出功能
 */
class ExportUtils {
    /**
     * 导出计价单到Excel文件
     * @param {Array} quotations 计价单数据
     * @param {string} filename 文件名
     * @returns {Promise<string>} 返回文件路径
     */
    async exportQuotationsToExcel(quotations, filename = 'quotations.xlsx') {
        const workbook = new ExcelJS.Workbook();
        const worksheet = workbook.addWorksheet('计价单列表');

        // 设置表头
        worksheet.columns = [
            { header: '计价单编号', key: 'id', width: 15 },
            { header: '区域', key: 'area_name', width: 20 },
            { header: '维修地点', key: 'location', width: 30 },
            { header: '维修人员', key: 'person', width: 15 },
            { header: '维修时间', key: 'repair_date', width: 20 },
            { header: '总价(元)', key: 'total_price', width: 15 },
            { header: '提交时间', key: 'created_at', width: 20 },
            { header: '维修项目明细', key: 'items_detail', width: 50 }
        ];

        // 设置表头样式
        worksheet.getRow(1).font = { bold: true };
        worksheet.getRow(1).fill = {
            type: 'pattern',
            pattern: 'solid',
            fgColor: { argb: 'FFE0E0E0' }
        };

        // 添加数据
        quotations.forEach(quotation => {
            let itemsDetail = '';
            try {
                const items = JSON.parse(quotation.items);
                itemsDetail = items.map(item => 
                    `${item.name}(${item.specification || ''}) ${item.quantity}${item.unit} ¥${item.price}`
                ).join('; ');
            } catch (e) {
                itemsDetail = quotation.items;
            }

            worksheet.addRow({
                id: quotation.id,
                area_name: quotation.area_name || '未知区域',
                location: quotation.location,
                person: quotation.person,
                repair_date: quotation.repair_date,
                total_price: quotation.total_price,
                created_at: quotation.created_at,
                items_detail: itemsDetail
            });
        });

        // 设置边框
        worksheet.eachRow((row, rowNumber) => {
            row.eachCell((cell) => {
                cell.border = {
                    top: { style: 'thin' },
                    left: { style: 'thin' },
                    bottom: { style: 'thin' },
                    right: { style: 'thin' }
                };
            });
        });

        // 保存文件
        const filePath = path.join(__dirname, '..', 'public', 'exports', filename);
        
        // 确保导出目录存在
        const exportDir = path.dirname(filePath);
        if (!fs.existsSync(exportDir)) {
            fs.mkdirSync(exportDir, { recursive: true });
        }

        await workbook.xlsx.writeFile(filePath);
        console.log(`Excel文件已导出: ${filePath}`);
        
        return filePath;
    }

    /**
     * 生成CSV导入模板
     * @param {string} filename 文件名
     * @returns {Promise<string>} 返回文件路径
     */
    async generateImportTemplate(filename = 'import_template.csv') {
        const csvContent = '维修内容,规格型号,单位,结算单价,备注\n' +
                          '示例：补加氟材料费及技术服务费,1P-1.5P挂机,次,80,\n' +
                          '示例：更换压机电容材料费及技术服务费,2P柜、挂机,台,50,';
        
        const filePath = path.join(__dirname, '..', 'public', 'templates', filename);
        
        // 确保模板目录存在
        const templateDir = path.dirname(filePath);
        if (!fs.existsSync(templateDir)) {
            fs.mkdirSync(templateDir, { recursive: true });
        }

        fs.writeFileSync(filePath, csvContent, 'utf8');
        console.log(`CSV模板已生成: ${filePath}`);
        
        return filePath;
    }

    /**
     * 清理过期的导出文件
     * @param {number} maxAge 最大保存时间（小时）
     */
    cleanupExportFiles(maxAge = 24) {
        const exportDir = path.join(__dirname, '..', 'public', 'exports');
        
        if (!fs.existsSync(exportDir)) {
            return;
        }

        const files = fs.readdirSync(exportDir);
        const now = Date.now();
        const maxAgeMs = maxAge * 60 * 60 * 1000;

        files.forEach(file => {
            const filePath = path.join(exportDir, file);
            const stats = fs.statSync(filePath);
            
            if (now - stats.mtime.getTime() > maxAgeMs) {
                fs.unlinkSync(filePath);
                console.log(`已清理过期文件: ${file}`);
            }
        });
    }
}

module.exports = new ExportUtils();